package com.easthome.controller;

import com.easthome.entity.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("test")
public class TestController {
    private Integer count = 0;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 时间间隔（分钟）
     */
    private static final int TIME_INTERVAL = 10;
    /**
     * 登录失败重试次数上限
     */
    private static final int FAILED_RETRY_TIMES = 3;
    /**
     * redis记录用户登录失败次数key
     */
    private static final String USER_LOGIN_FAILED_COUNT = "USER:LOGIN:FAILED:COUNT:";

    @PostMapping("resign")
    public Result yanzheng(@RequestBody Map<String,String> map, HttpServletResponse response){
        String key = USER_LOGIN_FAILED_COUNT + map.get("telephone");


        RedisAtomicInteger counter = getRedisCounter(key);
        //        模拟匹配失败
        counter.getAndIncrement();

        System.out.println(map);
        if (counter.get() >=FAILED_RETRY_TIMES){
            return new com.easthome.entity.Result(false,"您已多次验证失败，请一小时后重试！");
        }
        return new com.easthome.entity.Result(false,"登陆失败！");
    }

    private RedisAtomicInteger getRedisCounter(String key) {
        RedisAtomicInteger counter =
                new RedisAtomicInteger(key, stringRedisTemplate.getConnectionFactory());
        if (counter.get() == 0) {
            // 设置过期时间，10秒
            counter.expire(TIME_INTERVAL, TimeUnit.SECONDS);
        }
        return counter;
    }

}
